package com.minimalist.basic.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;

/**
 * SM4加解密工具类
 *
 * @author 11987
 */
public class Sm4Util {

    /**
     * 加密
     */
    public static String encrypt(String data) {
        byte[] keyBytes = hexToArray();
        SM4 sm4 = SmUtil.sm4(keyBytes);
        return sm4.encryptHex(data);
    }

    /**
     * 解密
     */
    public static String decrypt(String encryptedData) {
        byte[] keyBytes = hexToArray();
        SM4 sm4 = SmUtil.sm4(keyBytes);
        return sm4.decryptStr(encryptedData, CharsetUtil.CHARSET_UTF_8);
    }

    private static byte[] hexToArray() {
        String hexKey = "1234567890abcdef1234567890abcdef";
        int len = hexKey.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexKey.charAt(i), 16) << 4)
                    + Character.digit(hexKey.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
        String url = "jdbc:dm://hcsdyyds.com:30236/MINIMALIST?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&clobAsString=1";
        String username = "SYSDBA";
        String password = "222222";
        // 加密用户名和密码
        String encryptedUrl = Sm4Util.encrypt(url);
        String encryptedUsername = Sm4Util.encrypt(username);
        String encryptedPassword = Sm4Util.encrypt(password);
        System.out.println("Encrypted URL: " + encryptedUrl);
        System.out.println("Encrypted Username: " + encryptedUsername);
        System.out.println("Encrypted Password: " + encryptedPassword);
        String data = Sm4Util.decrypt("45120315175c0d64677e69e1315c9c20e36f5bd91a1414b9d7492264bcb8f795274f159802df9940e97ce9ce4ff90d40");

        System.out.println("decrypt: " + data);
    }
}
